<script setup lang="ts">
import { changePwdApi } from '@/api/login'
import { useUserStore, useNavTabStore } from '@/stores'
import type { PasswordRuleForm } from '@/types/login'
import { Check, Refresh } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance } from 'element-plus'
import type { FormRules } from 'element-plus/lib/components/index.js'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
const ruleFormRef = ref<FormInstance>()
const oneShow = ref(false)
const twoShow = ref(false)
const loginFrom = ref({
  oldPass: '',
  newPass: '',
  confirmPass: ''
})
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== loginFrom.value.newPass) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}
const rules = reactive<FormRules<PasswordRuleForm>>({
  oldPass: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 6, max: 20, message: '原密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  newPass: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '新密码长度在 6 到 20 个字符', trigger: 'blur' },
    {
      pattern: /^\S*(?=\S{6,20})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*?.])\S*$/,
      message: '密码必须包含大小写字母、数字和特殊字符(!@#$%^&*?)',
      trigger: 'blur'
    }
  ],
  confirmPass: [{ required: true, validator: validatePass2, trigger: 'blur' }]
})

const store = useUserStore() // 用户信息
const storeNav = useNavTabStore()
// 跳转路由
const router = useRouter()
const gotoPage = (path: string) => {
  router.push({
    path: `${path}`
  })
}
const refreshFn = () => {
  ruleFormRef.value?.resetFields()
}

const cgPassword = async () => {
  const params = {
    opwd: loginFrom.value.oldPass,
    npwd: loginFrom.value.newPass,
    rnpwd: loginFrom.value.confirmPass
  }
  await changePwdApi(params)
    .then((res: any) => {
      if (res.code === 0) {
        ElMessage({ message: res.message, type: 'success' })
        refreshFn()
        storeNav.clearNavTab()
        store.clearUserStore()
        gotoPage('/login')
      } else {
        ElMessage({ message: res.message, type: 'error' })
      }
    })
    .catch(() => {
      ElMessage({ message: '修改失败', type: 'error' })
    })
}
const submitForm = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate((valid) => {
    if (valid) {
      cgPassword()
    } else {
      ElMessage({ message: '信息填写有误', type: 'error' })
    }
  })
}
</script>
<template>
  <div class="passwordBox">
    <div class="passwordCon">
      <el-form ref="ruleFormRef" :model="loginFrom" :rules="rules">
        <el-form-item prop="oldPass">
          <el-input v-model="loginFrom.oldPass" placeholder="旧密码" class="input-with-select" />
        </el-form-item>
        <el-form-item prop="newPass">
          <el-input
            v-model="loginFrom.newPass"
            placeholder="新密码"
            class="input-with-select"
            :type="oneShow ? 'text' : 'password'"
          >
            <template #suffix>
              <svg-icon
                @click="oneShow = !oneShow"
                color="#444444"
                className="iconBox"
                :iconName="oneShow ? 'icon-eye' : 'icon-eye-close'"
              ></svg-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="confirmPass" class="verificationCode">
          <el-input
            v-model="loginFrom.confirmPass"
            placeholder="确认密码"
            class="input-with-select"
            :type="twoShow ? 'text' : 'password'"
          >
            <template #suffix>
              <svg-icon
                @click="twoShow = !twoShow"
                color="#444444"
                className="iconBox"
                :iconName="twoShow ? 'icon-eye' : 'icon-eye-close'"
              ></svg-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item style="padding-top: 10px">
          <el-button type="success" :icon="Check" @click="submitForm()">确认修改</el-button>
          <el-button type="primary" :icon="Refresh" @click="refreshFn()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<style scoped lang="less">
.passwordBox {
  position: relative;
  width: 100vw;
  height: calc(100vh - 120px);

  :deep(.passwordCon) {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -44%);
    width: 520px;
    height: 450px;
    .el-input__wrapper {
      height: 40px;
    }
    .el-form-item__content {
      justify-content: end;
      .el-button {
        height: 36px;
      }
    }
    .iconBox {
      width: 20px;
      height: 20px;
      cursor: pointer;
    }
  }
}
</style>
